<?php

class PhotosController extends AppController {
  //public $scaffold;
  public $helpers = array('Html', 'TWSForm', 'Paginator');
  public $components = array('Session','Util','Upload');
  public $name = 'Photos';
  public $paginate;

  function __construct($request=null, $response=null) {
    parent::__construct($request, $response);
    $this->paginate = array(
       /* 'limit' => Configure::read('App.pageResultLimit'),*/
        'order' => array(
            'Photo.image_order' => 'asc'
            ));
    //$this->loadModel('Album');
  }



//admin and public version
  function member_index($albumId) {
    //$albumInfo = $this->Album->find('first', array( 'fields'=>array('Album.id', 'Album.name', 'Category.id', 'Category.name'), 'conditions'=>array('Album.album_id'=>$albumId)));
    $photoGroupInfo = $this->Photo->Album->find('first', $this->_getOptions($albumId));
    if (empty($photoGroupInfo)) {
      $this->render('member_invalid');
    }
    $this->set(array('albumId' => $albumId, 'groupInfo' => $photoGroupInfo));
    //http://book.cakephp.org/view/1232/Controller-Setup -- Here is where you can pass in special conditions
    $this->set('photos', $this->paginate('Photo',
                    array('Photo.album_id' => $albumId)));
  }

  //public version
  function view($id=null) {
    $this->Photo->id = $id;
    $this->set('photos', $this->Photo->read());
    //TO-DO set the view here to the same as viewing all the announcements
  }

  function member_add($albumId) {
    $photoGroupInfo = $this->Photo->Album->find('first', $this->_getOptions($albumId));
    if (empty($photoGroupInfo)) {
      $this->render('member_invalid');
    }
    $this->set(array('albumId'=>$albumId,'groupInfo'=>$photoGroupInfo));
    if ($this->request->is('post')) {
      $this->_processAction($this->request, 'add');
    } 
  }
  
  function member_add_multiple($albumId) {
    $photoGroupInfo = $this->Photo->Album->find('first', $this->_getOptions($albumId));
    if (empty($photoGroupInfo)) {
      $this->render('member_invalid');
    }
    $this->set(array('albumId'=>$albumId,'groupInfo'=>$photoGroupInfo));
    if ($this->request->is('post')) {
      $this->render('member_invalid'); //handled in ImagesController
    } 
  }  

  //admin
  function member_edit($id = null) {
    //TODO - options have to be changed. We have the photo id here not the album id, the link  and possible category/album data will be incorrect
    $this->Photo->id = $id;
    if ($this->request->is('get')) {
     $photoGroupInfo = $this->Photo->Album->find('first', $this->_getOptions());
    if (empty($photoGroupInfo)) {
      $this->render('member_invalid');
    }
      $this->set(array('albumId'=> $photoGroupInfo['Album']['id'], 'groupInfo'=>$photoGroupInfo));
      $this->request->data = $this->Photo->read();
    } else {
      //check for delete announcement
      if (isset($this->request->data['deleteBtn'])) {
        $this->member_delete($id);
      } else {
        $this->_processAction($this->request, 'edit', $id);
      }
    }
  }

    function member_edit_ajax($id = null) {
    $result = array();
    if ($this->request->is('post')) {
      $data = $this->request->data;
      $this->Photo->id = $data['photoId'];
      $user = $this->Session->read('User');
      $updateResult = $this->Photo->save(array("Photo"=>array('caption'=>$data['photoCaption'])), false, array('caption','modified_by'));
      if (!empty($updateResult)) {
        $result = array('success'=>true, 'data'=>$updateResult, 'id'=>$data['photoId']);
      } else {
        $result = array('success'=>false, 'message'=>'The record was not successfully update. Please try again.');
      }
    }
    $json = array('result' => $result);
    $this->set('json', $json);
    $this->render('/Elements/json', '/json/default');
  }

  function member_update_sort(){
    if ($this->request->is('post')) {
      $postData = $this->request['data'];
      $albumId = $postData['albumId'];
      $count = 1;
      $done = false;
      $result = array();
      //Beginning a transaction
      $dataSource = $this->Photo->getDataSource();
      $dataSource->begin();
      while(!$done) {
        if (!empty($postData["photoId".$count])){
          $photoId = $postData["photoId".$count];
          $oldOrder = $postData["oldOrder".$count];
          $newOrder = $postData["newOrder".$count];
          if($oldOrder!==$newOrder) { //record has to be updated
            $this->Photo->id = $photoId;
            $updateResult = $this->Photo->save(array("Photo"=>array('image_order'=>$newOrder)), false, array('image_order', 'modified_by'));
            //Exit loop in the event of an error
            if(empty($updateResult)){
              break;
            }
          }
        } else {
          $done = true;
        }
        $count++;
      }
      if($done) {
        $dataSource->commit();
        $result['success']= true;
        //get photos from album
        $sortedPhotos = $this->Photo->find('all', array('conditions'=>array('Photo.album_id'=>$albumId),'order'=>array('Photo.image_order ASC')));
        $photoResults = array();
        if(!empty($sortedPhotos)){
          foreach($sortedPhotos as $sortedPhoto){
            array_push($photoResults, array("id"=>$sortedPhoto['Photo']['id'], 'caption'=>$sortedPhoto['Photo']['caption'],'image_path'=>$sortedPhoto['Photo']['image_path'],'image_thumb_path'=>$sortedPhoto['Photo']['image_thumb_path'],'image_order'=>$sortedPhoto['Photo']['image_order']));
          }
        }
        $result['data']=array('albumId'=>$albumId, 'photos'=>$photoResults);
      } else {
        $dataSource->rollback();
          throw new Exception('An error occurred and the sort order was not updated. Please try again.');
      }
      $json = array('result' => $result);
      $this->set('json', $json);
      $this->render('/Elements/json', '/json/default');

    }
  }

  private function _processAction($dataIn, $action='add', $id=null) {
    $data = $this->_processRequestData($dataIn);
    if ($action === "add") {
      $this->Photo->set($data);
      if ($this->Photo->validates()) {
        if (!empty($data["Photo"]["image_path"]) && !empty($data["Photo"]["image_path"]['name'])) {
          $albumId = $data["Photo"]["album_id"];
          $specialAlbum = null;
          //Checking so see if this is an administraive album that has to be handled specially
          foreach(Configure::read('App.administrativeAlbums') as $key=>$adminAlbum) {
            if($adminAlbum['id']==$albumId) {
             $specialAlbum = $adminAlbum;
            }
          }
          $albumsFolder = empty($specialAlbum) ? Configure::read('App.defaultAlbumsImageFolder') : $specialAlbum['imageFolder'];
          $fileName = $albumId . '_' . $this->Util->cleanFileName($data["Photo"]["image_path"]['name'], true) . "_" . date("U");
          $desiredWidth = empty($specialAlbum) ? null : $specialAlbum['width'];
          $desiredHeight = empty($specialAlbum) ? null : $specialAlbum['height'];
          $desiredThumbWidth = !empty($specialAlbum) && !empty($specialAlbum['thumbWidth']) ? $specialAlbum['thumbWidth']: Configure::read('App.photoImageThumbWidth');
          $imageUploaded = $this->Upload->uploadImage($data["Photo"]["image_path"], WWW_ROOT . '/' . Configure::read('App.imageFolder') . '/' . $albumsFolder, $desiredWidth, $desiredHeight, $fileName, true, $desiredThumbWidth);
          $data["Photo"]["image_path"] = $albumsFolder . '/' . $imageUploaded;
          $data["Photo"]["image_thumb_path"] = $albumsFolder . '/' . Configure::read('App.defaultThumbnailPrefix') . $imageUploaded;
        }
        if ($this->Photo->save($data, false)) {
          $this->Session->setFlash('The record was successfully saved.');
          $this->redirect(array('action' => 'index', 'member'=>true, $data["Photo"]["album_id"]));
        }       
      } else {
        $this->request->data['Photo'] = $data['Photo'];
        $this->set('errors', $this->Photo->validationErrors);
        $this->render('member_add');
      }
    } elseif($action === "edit") {
      $originalRec = $this->Photo->find("first", array("conditions" => array("Photo.id" => $id)));
      $this->Photo->set($data);
      if ($this->Photo->validates()) {
        //update record
        if ($this->Photo->save($data, false, array('caption'))) {
          $this->Session->setFlash('The record was successfully saved.');
          $this->redirect(array('action' => 'index', 'member' => true, $originalRec["Photo"]["album_id"]));
        }
      } else {
        $data['Photo']['image_path'] = $originalRec["Photo"]["image_path"];
        $data['Photo']['id'] = $id;
        $this->request->data['Photo'] = $data['Photo'];
        $this->set('errors', $this->Photo->validationErrors);
        $this->render('member_edit');
      }      
    } 
  }
  
  function member_delete($id) {
    $album = $this->Photo->read('album_id',$id);
    if(!empty($album)) {
      $this->deleteImage($id);
      if ($this->Photo->delete($id)) {
        $this->Session->setFlash('The photo has been deleted.');
        $this->redirect(array('action' => 'index','admin'=>true, $album['Photo']['album_id']));
      }
    } else {$this->render('member_invalid');}
  }

    function deleteImage($id) {
      //TODO - Images are not being deleted
    $retVal = false;
    $image = $this->Photo->read(array('image_path','image_thumb_path'), $id);
    $imagePath = $image['Photo']['image_path'];
    $imageThumbPath = $image['Photo']['image_thumb_path'];
    if (!empty($imagePath)) {
      $result = $this->Util->deleteFile(WWW_ROOT . '/' . Configure::read('App.imageFolder') . '/' . $imagePath);
      $resultThumb = $this->Util->deleteFile(WWW_ROOT . '/' . Configure::read('App.imageFolder') . '/' . $imageThumbPath);
      $retVal = $result && $resultThumb;
    }
    return $retVal;
  }

  private function _getOptions($albumId=null) {
    $options = array();
     ////http://book.cakephp.org/view/1047/Joining-tables --joins
    //Get category name and album name
    if(!empty($albumId)){
      $options['conditions'] = array(
        'Album.id' => $albumId
      );
    }
    $options['fields']= array (
        'Album.id', 'Album.name', 'Category.id', 'Category.name' //Use Category alias here
    );
    return $options;
  }

  function member_invalid(){
  //Throw 404 Exception
    throw new NotFoundException('The url that was entered was not valid');
  }

}

?>
